package uploadfiletoserver;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//解析JSON文件
public class GetJSON {
    public static void readJSON(){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            File info = new File("info.json");
            JsonNode rootNode = objectMapper.readTree(info);

            //解析服务器列表
            List<Server> serverList = new ArrayList<>();
            //获取服务器列表
            JsonNode serversNode = rootNode.get("servers");
            for (JsonNode jsonNode : serversNode) {
                //获取服务器的地址
                String address = jsonNode.get("address").asText();
                //获取端口
                int port = jsonNode.get("port").asInt();
                //获取用户名
                String username = jsonNode.get("username").asText();
                //获取密码
                String password = jsonNode.get("password").asText();
                //获取邮箱
                String adminEmail = jsonNode.get("adminEmail").asText();
                //创建集合存放要发送的所有文件
                List<String> fileToSend = new ArrayList<>();
                //从json文件中获取要发送的文件
                JsonNode filesNode = jsonNode.get("files");
                for (JsonNode fileNode : filesNode) {
                    //获取路径
                    String path = fileNode.asText();
                    //把每个文件添加到集合中
                    fileToSend.add(path);
                }

                UploadFile.uploadFile(address,port,username,password,adminEmail,fileToSend);
                //创建服务器对象
                Server server = new Server(address,port,username,password,adminEmail,fileToSend);
                //将服务器添加到集合中
                serverList.add(server);
            }
            ExecutorService service = Executors.newFixedThreadPool(serverList.size());
            for (Server server : serverList) {
                service.execute(new ServerCheck(server));
            }
            service.shutdown();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
